package cn.net.isir.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.net.isir.common.config.WxConfig;
import cn.net.isir.utils.HttpUtil2;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxubo
 * @filename WxAccessTokenManager.java
 * @package cn.net.isir.common
 * @email lxb@isir.net.cn
 * @date 2019/01/02
 * @comment 微信全局token管理类
 * @since 1.8
 */
public class WxAccessTokenManager {
    private static String token = null;
    private static Date expireTime = null;

    /**
     * 获取token
     * @return 获取token
     */
    public static String getAccessToken() {
        if (expireTime == null || expireTime.before(new Date())) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("appid", WxConfig.getSub_appid());
            paramMap.put("secret", WxConfig.getSub_appSecret());
            paramMap.put("grant_type", "client_credential");
            String getOpenIdUrl = "https://api.weixin.qq.com/cgi-bin/token";
            String resultStr = HttpUtil2.sendGetByUrlConnection(getOpenIdUrl, paramMap, "utf-8");
            JSONObject jsonObject = JSON.parseObject(resultStr);
            Object access_token = jsonObject.get("access_token");
            if (access_token != null){
                token = String.valueOf(String.valueOf(access_token));
                int seconds = Integer.parseInt(String.valueOf(jsonObject.get("expires_in")));
                expireTime = new Date(new Date().getTime() + (seconds - 60) * 1000);//减60表示提前一分钟重新获取
                return token;
            }
        }
        return token;
    }

}
